<?php

namespace qiniu\rs;

use yii\base\InvalidConfigException;
use yii\base\Object;
use Yii;

class PutPolicy extends Object
{
    public $scope;

    public $deadline;

    public $insertOnly;

    public $saveKey;

    public $endUser;

    public $callbackUrl;

    public $callBackBody;

    public $callbackHost;

    public $returnUrl;

    public $returnBody;

    public $persistentOps;

    public $persistentNotifyUrl;

    public $persistentPipeline;

    public $fsizeLimit;

    public $detectMime;

    public $mimeLimit;

    public $extensions;

    public function init()
    {
        if (!isset($this->scope)) {
            throw new InvalidConfigException('scope not set');
        }

        if (!isset($this->deadline)) {
            $this->deadline = time() + 60;
        }

        if (isset($this->extensions)) {
            if (!is_array($this->extensions)) {
                $this->extensions = preg_split('/\s*,\s*/', $this->extensions, -1, PREG_SPLIT_NO_EMPTY);
            }
            $allowMimes = [];
            $mimeTypes = require_once(Yii::getAlias('@yii/helpers/mimeTypes.php'));
            foreach ($this->extensions as $ext) {
                if (isset($mimeTypes[$ext])) {
                    $allowMimes[] = $mimeTypes[$ext];
                }
            }
            $this->mimeLimit = implode(';', $allowMimes);
            unset($this->extensions);
        }
    }

    /**
     * @inheritdoc
     */
    public function json()
    {
        $vars = [];
        foreach (get_object_vars($this) as $name => $value) {
            if ($value !== null) {
                $vars[$name] = $value;
            }
        }
        return json_encode($vars);
    }
}
